from typing import Sequence

from pynumpak.general import Func


class Linear(Func):
    def __init__(self, nodes: Sequence, values: Sequence):
        assert len(nodes) == len(values)
        self.nodes = nodes
        self.values = values

    def compute(self, x: float):
        left_node = -1
        right_node = -1
        for i in range(len(self.nodes)):
            if self.nodes[i] < x:
                if left_node == -1:
                    left_node = i
                elif self.nodes[left_node] < self.nodes[i]:
                    left_node = i
            elif self.nodes[i] > x:
                if right_node == -1:
                    right_node = i
                elif self.nodes[right_node] > self.nodes[i]:
                    right_node = i
            else:
                assert self.nodes[i] == x
                return self.values[i]

        if left_node == -1 or right_node == -1:
            raise (ValueError("x needs to lie between nodes"))

        # computing
        return ((self.nodes[right_node] - x) * self.values[left_node] + (x - self.nodes[left_node]) *
                self.values[right_node]) / (self.nodes[right_node] - self.nodes[left_node])
